<template>
  <el-form
    ref="formData"
    label-width="120px"
    class="keywords_add_body"
    :model="formData"
    :disabled="isDisabled"
  >
    <!-- 商品关键词 -->
    <el-form-item
      prop="keywordName"
      label="商品关键词："
      :rules="{ required: true, message: '商品关键词不能为空', trigger: 'change' }"
    >
      <el-input
        v-model.trim="formData.keywordName"
        placeholder="请输入商品关键词"
        show-word-limit
        :maxlength="20"
        @input="handleInputByKeyword"
        @blur="handleBlurKeyword"
      ></el-input>
    </el-form-item>
    <slot name="middle_slot"></slot>
    <el-form-item v-if="formData.recommendAliasNames" label="系统推荐别名：">
      <span>{{ formData.recommendAliasNames }}</span>
    </el-form-item>
    <!-- 已有别名（仅做展示） -->
    <el-form-item v-if="formData.existAliasNamesStr" label="已有别名：">
      <span>{{ formData.existAliasNamesStr }}</span>
    </el-form-item>
    <!-- 别名 -->
    <div class="alias_wrap">
      <el-form-item
        v-for="(item, index) in formData.aliasInfoList"
        :key="index"
        :prop="`aliasInfoList.${index}.aliasName`"
        :label="`别名${index === 0 ? '' : index + 1}：`"
      >
        <el-row type="flex">
          <el-input
            v-model.trim="item.aliasName"
            placeholder="请输入别名"
            class="margin_right"
          ></el-input>
          <template v-if="!isDisabled">
            <el-button
              v-if="index === 0"
              icon="el-icon-plus"
              circle
              @click="addAlias"
              :disabled="isEqualToMaxAmount()"
            ></el-button>
            <el-button
              v-if="index !== 0"
              icon="el-icon-minus"
              circle
              @click="() => { deleteAlias(index) }"
            ></el-button>
          </template>
        </el-row>
      </el-form-item>
    </div>
    <slot name="end_slot"></slot>
  </el-form>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { isResponseSuccess } from '@/utils/bizUtils';
import { REPLACE_SPECIAL_SYMBOLS } from '@/constants/regExp';
export default {
  props: {
    maxAmount: { // 最大别名数量
      type: Number,
      default: 100
    },
    dataSource: { // 已有数据 - 编辑页
      type: Object
    },
    productName: { // 商品名称
      type: String,
      default: ''
    },
    isDisabled: { // 表单是否禁用
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      formData: {
        keywordName: '',
        aliasInfoList: [{ aliasName: '' }],
        recommendAliasNames: '', // 系统推荐别名
        existAliasNamesStr: '', // 已有别名拼接字符串
      },
      selectLoading: false,
      apiObj: {
        getByExactKeyword: { // 获取关键词下拉集合 - 精确查询
          url: '/sysback/product/keyword/getByExactKeyword',
          type: 'get'
        }
      }
    }
  },
  watch: {
    dataSource: {
      deep: true,
      immediate: true,
      handler (data) {
        if (data) {
          this.setFormData(data);
        }
      }
    },
  },
  methods: {
    // 别名数量等于最大限制数量
    isEqualToMaxAmount () {
      return this.formData.aliasInfoList.length >= this.maxAmount;
    },
    // 当前集合为空
    isEmptyForCurrentList (list = this.formData.aliasInfoList) {
      if (!list) { return true; }
      return list.length === 0;
    },
    // 设置formData
    setFormData (data) {
      const { keywordUuid, keywordName, aliasInfoList, recommendAliasNames } = data;
      this.formData = {
        keywordName,
        keywordUuid,
        aliasInfoList: this.isEmptyForCurrentList(aliasInfoList) ? [{ aliasName: '' }] : aliasInfoList,
        recommendAliasNames
      }
    },
    // 输入关键词
    handleInputByKeyword (val) {
      this.formData.keywordName = val.replace(REPLACE_SPECIAL_SYMBOLS, '');
    },
    // 关键词输入框失去焦点
    handleBlurKeyword () {
      if (!this.formData.keywordName) { return false; }
      if (!this.validateIncludesBrandName(this.formData.keywordName)) {
        return this.$message.warning('关键词需要包含在商品名称中');
      }
      this.getKeywordsByRemotePrecise(this.formData.keywordName)
    },
    // 远程精确请求关键词下拉集合
    async getKeywordsByRemotePrecise (val) {
      const { url, type } = this.apiObj.getByExactKeyword;
      const retData = await this.getOptionsByKeywords({ url: `${url}?exactKeyword=${val}`, type });
      if (retData) {
        this.formData.existAliasNamesStr = retData.aliasNames.map(item => item.aliasName).join('，');
        this.formData.aliasInfoList = [{ aliasName: '' }];
      } else {
        this.formData.existAliasNamesStr = '';
        this.$forceUpdate();
      }
    },
    // 新增别名
    addAlias () {
      this.formData.aliasInfoList.push({ aliasName: '' });
    },
    // 删除别名
    deleteAlias (index) {
      this.formData.aliasInfoList.splice(index, 1);
    },
    // 获取提交结果
    getResultBySubmit () {
      return new Promise(resolve => {
        this.$refs.formData.validate(valid => {
          if (!valid) { // 必填校验
            return this.$message.warning('请完整填写必填内容');
          }
          resolve({
            ...this.formData,
            aliasInfoList: (this.formData?.aliasInfoList || []).filter(item => item.aliasName)
          });
        });
      });
    },
    // 校验别名包含品牌名
    validateIncludesBrandName (val) {
      if (!val) { return true; }
      const preValidateList = val.toLowerCase().split('');
      const validateResult = [];
      preValidateList.forEach(item => {
        const index = this.productName.toLowerCase().indexOf(item);
        if (index !== -1) {
          validateResult.push(true);
        } else {
          validateResult.push(false);
        }
      });
      return validateResult.every(item => item);
    },
    // 获取关键词下拉集合
    async getOptionsByKeywords ({ url, type, data = {}, isFormData = false }) {
      try {
        this.selectLoading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.selectLoading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
      } catch (err) {
        this.selectLoading = false;
      }
    },
  }
}
</script>
<style lang="less" scoped>
.alias_wrap {
  max-height: 300px;
  overflow: hidden;
  overflow-y: auto;
  padding-right: 20px;
}
.keywords_add_body {
  max-width: 50%;
}
.margin_right {
  margin-right: 20px;
}
</style>
